package com.mysteel.cyx.demo.biz.threadlocal;


import java.util.concurrent.*;

/**
 * ttl测试
 *
 * @author cyx
 * @date 2024-04-07 12:47
 */
public class InheritableThreadLocalTest {

    // 1. InheritableThreadLocal
    static InheritableThreadLocal<String> local = new InheritableThreadLocal<>();

    // 初始化一个长度为1的线程池
    static ExecutorService poolExecutor = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws InterruptedException {

        InheritableThreadLocalTest test = new InheritableThreadLocalTest();
        test.test();
    }

    private void test() throws InterruptedException {

        // 设置初始值
        local.set("天王老子");


        // 创建三个任务并提交给线程池
        for (int i = 0; i < 10; i++) {
            poolExecutor.submit(new Task("任务" + i));
        }
        System.out.println("父线程的值：" + local.get());
        poolExecutor.shutdown();
    }

    class Task implements Runnable {

        String str;

        Task(String str) {
            this.str = str;
        }

        @Override
        public void run() {
            // 获取值
            System.out.println(Thread.currentThread().getName() + ",before:" + local.get());
            // 重新设置一波
            local.set(str);
            // 获取值
            System.out.println(Thread.currentThread().getName() + ",after:" + local.get());
        }
    }
}